package com.gthncz.hello.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gthncz.hello.beans.User;
import com.gthncz.hello.common.CommonResult;
import com.gthncz.hello.dto.UserLoginParam;
import com.gthncz.hello.service.UserAdminService;


/**
 * 登录控制逻辑：
 * 这里是后端，而前端由独立的应用开发
 * 后端启动 tomcat ，在 8080 端口监听数据请求
 * 前端通过 npm run dev 在 8090 端口提供页面访问
 * 
 * @author GT
 * @param <CommonResult>
 *
 */

@Controller
@RequestMapping(value = "/admin")
@PreAuthorize("hasRole('ROLE_ADMIN')") // 需要 ADMIN 才能使用
public class LoginAdminController {
	
	@Autowired
	private UserAdminService userAdminService;
	
	@RequestMapping(value = "/loginPost", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult<User> loginPost(@ModelAttribute UserLoginParam userLoginParam, BindingResult result) {
		User user = userAdminService.login(userLoginParam);
		if(user == null) {
			return CommonResult.validateFailed("用户名或者密码不正确!");
		} else {
			return CommonResult.success(user, "登录成功!");
		}
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model) {
		model.addAttribute("userLoginParam", new UserLoginParam());
		return "login";
	}
	
}
